package com.zr.service.impl;

import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;

import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.poi.ss.usermodel.Cell;
import org.apache.poi.ss.usermodel.Row;
import org.apache.poi.ss.usermodel.Sheet;
import org.apache.poi.ss.usermodel.Workbook;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;

import com.zr.dao.E_userDao;
import com.zr.dao.impl.E_userDaoImpl;
import com.zr.service.AddMoreUserService;

public class AddMoreUserServiceImpl implements AddMoreUserService {
	private E_userDao userDao = new E_userDaoImpl();

	@Override
	public String getAddMoreUserByExcel(File file) {
		String msg = this.importUser(file);
		return msg;
	}

	@Override
	public String importUser(File file) {
		Workbook workbook = null;
		try {
			// 创建对Excel 工作薄文件的引用
			workbook = new XSSFWorkbook(new FileInputStream(file));
		} catch (Exception e) {
			try {
				workbook = new HSSFWorkbook(new FileInputStream(file));
			} catch (IOException e1) {
				e1.printStackTrace();
			}
		}
		int countSuccess = 0;
		int countLose = 0;
		int count = 0;
		// 创建对工作表的引用
		Sheet sheet = workbook.getSheetAt(0);
		int j = 0;// 从第一行开始读数据
		while (j < sheet.getPhysicalNumberOfRows()) {
			String uname = null;
			int rid;
			try {
				Row row = sheet.getRow(j);
				if(row.getPhysicalNumberOfCells()>2){
					return "要导入的Excel表数据错误";
				}
				Cell cell0 = row.getCell(0);
				Cell cell1 = row.getCell(1);
				uname = cell0.getStringCellValue();
				rid = (int) cell1.getNumericCellValue();
			} catch (Exception e) {
				return "要导入的Excel表数据错误";
			}
			boolean b = userDao.selectUserNameByUname(uname);
			if (b) {
				count++;
			} else {
				boolean b1 = userDao.addUser(uname, "123456", rid);// 用户默认密码为123456
				if (b1) {
					countSuccess++;
				} else {
					countLose++;
				}
			}
			j++;
		}
		StringBuffer msg = new StringBuffer();
		msg.append("添加成功:" + countSuccess + "<br>");
		msg.append("添加失败:" + countLose + "<br>");
		msg.append("已存在用户:" + count);
		return msg.toString();
	}

}
